package teacher;

import admin.Connectmysql;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;

@WebServlet("/ExamCancelServlet")
public class ExamCancelServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int examId = Integer.parseInt(request.getParameter("exam_id"));
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        if (teacherId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        try {
            Connectmysql conn = new Connectmysql("jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver");
            if (conn.open()) {
                // 检查考试状态和权限
                String checkSql = "SELECT * FROM exam WHERE exam_id = ? AND teacher_id = ? AND status = 0";
                ResultSet rs = conn.executeSql(checkSql, new Object[]{examId, teacherId});

                if (rs.next()) {
                    // 取消考试
                    String deleteSql = "DELETE FROM exam WHERE exam_id = ?";
                    int result = conn.executeSqlUpdate(deleteSql, new Object[]{examId});

                    if (result > 0) {
                        response.sendRedirect("teacher.jsp?section=exam&msg=考试申请已取消");
                    } else {
                        response.sendRedirect("teacher.jsp?section=exam&error=取消失败");
                    }
                } else {
                    response.sendRedirect("teacher.jsp?section=exam&error=无法取消已批准的考试");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("teacher.jsp?section=exam&error=数据库错误");
        }
    }
}